<?php

/*
 * Created on Dec 7, 2013
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
class Question_model extends CI_Model {

	public function __construct() {
		$this->load->database();
	}
	
	public function get_question($id){
  		$query = $this->db->get_where('tb_question', array('id' => $id));
  		return $query->row_array();
	}
	
	public function question_insert($arr){
//		echo '-----------';
//		var_dump($arr);
//		echo '-----------';
		$this->db->insert('tb_question', $arr);
	}
	
	public function question_update($id, $arr){
		$this->db->where('id', $id);
		$this->db->update('tb_question', $arr);
	}
	
	public function question_delete($id){
		$this->db->where('id', $id);
		$this->db->delete('tb_question');
	}
	
	public function list_question($search, $limit = false, $offset = 0){
		$sql = "select * from tb_question where 1 = 1 ";
		$arr = array();
		if(isset($search['q_title']) && $search['q_title'] != ''){
			$sql .= "and title = ? ";
			$arr[] = $search['q_title'];
		}
		if(isset($search['q_section']) && $search['q_section'] != ''){
			$sql .= "and section = ? ";
			$arr[] = $search['q_section'];
		}
		if(isset($search['q_answer_str']) && $search['q_answer_str'] != ''){
			$sql .= "and INSTR(answer_str, ?) > 0 ";
			$arr[] = $search['q_answer_str'];
		}
		if(isset($search['desc']) && isset($search['sort']) && $search['sort'] != ''){
			$sql .= " order by ".$search['sort']." ".($search['desc'] == '1'?'desc':'asc');
		}
		if($limit){
			$sql .= " limit ".$offset.", ".$limit."";
		}
		$query = $this->db->query($sql, $arr);
		return $query->result_array();
	}
	
	public function count_question($search){
		$sql = "select count(*) res from tb_question where 1 = 1 ";
		$arr = array();
		if(isset($search['q_title']) && $search['q_title'] != ''){
			$sql .= "and title = ? ";
			$arr[] = $search['q_title'];
		}
		if(isset($search['q_section']) && $search['q_section'] != ''){
			$sql .= "and section = ? ";
			$arr[] = $search['q_section'];
		}
		if(isset($search['q_answer_str']) && $search['q_answer_str'] != ''){
			$sql .= "and INSTR(answer_str, ?) > 0 ";
			$arr[] = $search['q_answer_str'];
		}
		$query = $this->db->query($sql, $arr);
		return $query->row()->res;
	}
}

